//
//  ST_DaliyMomentDetialHeaderView.swift
//  btvideo
//
//  Created by mac on 2020/7/23.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SDWebImage
import SwiftyUserDefaults

class ST_DaliyMomentDetialHeaderView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        self.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(44)
            make.top.equalToSuperview().offset(23)
            make.left.equalToSuperview().offset(19)
        }
        
        self.addSubview(icon_supplement_image_view)
        icon_supplement_image_view.snp.makeConstraints { (make) in
            make.center.equalTo(avatar_image_view)
            make.width.height.equalTo(60)
        }
        
        self.addSubview(username_label)
        username_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(73)
            make.top.equalToSuperview().offset(25)
            make.height.equalTo(22)
        }
        
        self.addSubview(follow_btn)
        follow_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(avatar_image_view)
            make.height.equalTo(30)
            make.width.equalTo(56)
        }
        
        
        self.addSubview(time_label)
        time_label.snp.makeConstraints { (make) in
            make.left.equalTo(username_label)
            make.top.equalTo(username_label.snp.bottom).offset(1)
            make.height.equalTo(17)
        }
        
        
        self.addSubview(signView)
        signView.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.width.equalTo(70)
            make.centerY.equalTo(username_label)
            make.left.equalTo(username_label.snp.right).offset(4)
        }
        
        self.addSubview(dailySignView)
        dailySignView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(75)
            make.left.equalToSuperview().offset(69)
            make.height.equalTo(ST_DailyMomentSignView.height)
        }
        
        
        self.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(69)
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(109)
            make.size.equalTo(CGSize.zero)
        }
        
        self.addSubview(imageContainer)
        imageContainer.snp.makeConstraints { (make) in
            make.top.equalTo(content_label.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(69)
            make.size.equalTo(CGSize.zero)
        }
        
        
        self.addSubview(playerView)
        playerView.snp.makeConstraints { (make) in
            make.edges.equalTo(imageContainer)
        }
        
        
        self.addSubview(comment_btn)
        comment_btn.snp.makeConstraints { (make) in
            make.height.equalTo(44)
            make.right.equalToSuperview().offset(-15)
            make.bottom.equalToSuperview().offset(-51)
        }
        
        self.addSubview(thumbUpBtn)
        thumbUpBtn.snp.makeConstraints { (make) in
            make.right.equalTo(comment_btn.snp.left).offset(-20)
            make.height.centerY.equalTo(comment_btn)
        }
        
        self.addSubview(commentLabel)
        commentLabel.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-10)
            make.left.equalToSuperview().offset(15)
            make.height.equalTo(30)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //    MARK: - Properties
    fileprivate lazy var avatar_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 44/2.0
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(push_user_center_handle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
        return control
    }()
    
    fileprivate lazy var icon_supplement_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        return control
    }()
    
    fileprivate lazy var signView:ST_UserSignView = {
        let control = ST_UserSignView()
        return control
    }()
    
    fileprivate lazy var username_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var time_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.init(hexString: "#ACB4C0")
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var imageContainer:ST_DailyMomentImageContainer = {
        let control = ST_DailyMomentImageContainer()
        return control
    }()
    
    fileprivate lazy var playerView:ST_PeculiarityVideoPlayView = {
        let control = ST_PeculiarityVideoPlayView()
        control.isUserInteractionEnabled = false
        control.backgroundColor = UIColor.clear
        control.clipsToBounds = true
        control.alwaysHiddenPlaySign = true
        control.isMuted = true
        control.playDidFinishClosure = {[weak self] in
            self?.play_loop()
        }
        
        control.cornerRadius = 15
        return control
    }()
    
    fileprivate lazy var dailySignView:ST_DailyMomentSignView = {
        let control = ST_DailyMomentSignView()
        control.addTarget(self, action: #selector(pushSomeDailyHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var content_label:YYLabel = {
        let control = YYLabel()
        control.numberOfLines = 0
        
        let unfoldActionStr = NSMutableAttributedString.init(string: "...展开")
        
        let hi = YYTextHighlight()
        
        let action:YYTextAction = {[weak self] containerView, text, range, rect in
            
            guard let fold = self?.model?.isFoldContent else{
                return
            }
            
            self?.model?.isFoldContent = !fold
            
            self?.reload_cell_closure?()
        }
        
        hi.tapAction = action
        
        unfoldActionStr.yy_setColor(UIColor.init(hex: 0x42CEDA), range: NSRange.init(location: 3, length: 2))
        
        unfoldActionStr.yy_setTextHighlight(hi, range: NSRange.init(location: 3, length: 2))
        
        unfoldActionStr.yy_font = UIFont.systemFont(ofSize: 15)
        
        let seeMore = YYLabel()
        seeMore.attributedText = unfoldActionStr
        seeMore.sizeToFit()
        
        let truncationToken = NSAttributedString.yy_attachmentString(withContent: seeMore, contentMode: UIView.ContentMode.center, attachmentSize: seeMore.size, alignTo: UIFont.systemFont(ofSize: 15), alignment: YYTextVerticalAlignment.center)
        
        truncationToken.yy_setBaselineOffset(-2, range: NSRange.init(location: 0, length: truncationToken.length))
        
        control.truncationToken = truncationToken
        
        return control
    }()
    
    fileprivate lazy var thumbUpBtn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImage(ST_ImageUtils.imageName("thumb_up_mid_normal"), for: UIControl.State.normal)
        control.setImage(ST_ImageUtils.imageName("thumb_up_mid_selected"), for: UIControl.State.selected)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.contentHorizontalAlignment = .left
        control.setTitleColorForAllStates(UIColor.init(hex: 0xACB4C0)!)
        control.addTarget(self, action: #selector(thumb_up_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    var comment_click_closure:(()->())?
    
    fileprivate lazy var comment_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImage(ST_ImageUtils.imageName("comment_icon"), for: UIControl.State.normal)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.contentHorizontalAlignment = .left
        control.setTitleColorForAllStates(UIColor.init(hex: 0xACB4C0)!)
        control.addTarget(self, action: #selector(commentClickHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var follow_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0x42CEDA)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)
        control.cornerRadius = 30/2.0
        control.setTitle("喜欢", for: UIControl.State.normal)
        control.setTitleColor(UIColor.white, for: UIControl.State.normal)
        
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xF2F4F7)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.selected)
        
//        control.setTitle("已喜欢", for: UIControl.State.selected)
        control.setTitleColor(UIColor.init(hex: 0x333333)!, for: UIControl.State.selected)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.semibold)
        
        control.addTarget(self, action: #selector(follow_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    
    fileprivate lazy var commentLabel:UILabel = {
        let control = UILabel.init()
        control.text = "评论"
        control.textColor = UIColor.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    var reload_cell_closure:(()->())?
    
    //    MARK: - Play Video
    fileprivate func play_loop(){
        self.playerView.replay()
    }
    
    func play(){
        
        
        guard let videoUrl = model?.dailyContent.contentImages.first?.videoUrl else{
            return
        }
        
        stopVideo()
        
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
        }catch{
            print("AVAudioSession.Category.playback Error")
        }
        
        print("开始播放URL:",videoUrl)
        
        guard let url = videoUrl.url else{
            return
        }
        
        playerView.alpha = 1
        
        //        if m.width > m.height{
        playerView.play(url: url, gravity: AVLayerVideoGravity.resizeAspect)
        //        }else{
        //            playerView.play(url: url)
        //        }
    }
    
    func stopVideo(){
        
        
        playerView.stop()
        playerView.alpha = 0
        
    }
    
    func continuePlay(){
        
        playerView.continuePlay()
    }
    
    func pause_video(){
        
        playerView.pause()
    }
    
    //    MARK: - Bind Model
    weak var model:ST_DaliyMomentDetialHeaderModel?{
        didSet{
            
            guard let m = model else{
                return
            }
            
            model?.foldClosure = {[weak self] in
                self?.reload_cell_closure?()
            }
            
            avatar_image_view.sd_setImage(with: m.userInfo.avatar.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image(), options: SDWebImageOptions(), context: nil)
            
            icon_supplement_image_view.pin_setImage(from: AVATAR_SUPPLEMENT(guardTime: m.userInfo.guardTime, guardContent: m.userInfo.guardContent)?.url)
            
            
            username_label.text = m.userInfo.nickname
            
            time_label.text = m.dailyContent.createStr
            
            signView.bind_data(isVip: m.userInfo.isVip, detectedFace: m.userInfo.detectedFace)
            
            imageContainer.snp.updateConstraints { (make) in
                make.size.equalTo(m.mediaSize)
            }
            
            imageContainer.imagesArray = m.dailyContent.contentImages
            
            if let videoURL = imageContainer.imagesArray.first?.videoUrl,videoURL.count > 2{
                self.play()
            }
            
            
            dailySignView.bind(text: m.dailyContent.name, url: m.dailyContent.image)
            
            content_label.attributedText = m.contetnAttriStr
            
            content_label.snp.updateConstraints { (make) in
                make.top.equalToSuperview().offset(m.contentTopConstraint)
                if m.isFoldContent{
                    make.size.equalTo(m.foldContentSize)
                }else{
                    make.size.equalTo(m.unfoldContentSize)
                }
            }
            
            thumbUpBtn.isSelected = m.dailyContent.isThumbUp
            
            thumbUpBtn.setTitleForAllStates(m.dailyContent.thumpCount.st_number_description() + "  ")
            
            comment_btn.setTitleForAllStates(m.dailyContent.commentCount.st_number_description() + "  ")
            
//            follow_btn.isSelected = m.userInfo.isAttention
            
            
            
            follow_btn.isHidden = m.userInfo.accid == Defaults[.currentUserID] || m.userInfo.isAttention
            
        }
    }
    
}



extension ST_DaliyMomentDetialHeaderView{
    
    
    @objc fileprivate func commentClickHandle(){
        self.comment_click_closure?()
    }
    
    @objc fileprivate func thumb_up_click_handle(){
        
        guard let m = self.model else { return  }
        
        
        if m.userInfo.accid == ST_BTUserInfoManager.shared.current_account_info?.accid{
            
            let thumbUpHud = ST_BTHUDController.init(noticeText: "不能给自己点赞哦")
            
            GlobalPresent(toController: thumbUpHud, animated: false)
            
            main_thread_execute(afterDelay: 2.5) {
                thumbUpHud.dismiss(animated: false, completion: nil)
            }
            
            return
        }
        
        self.thumbUpBtn.isUserInteractionEnabled = false
        
        let api = self.thumbUpBtn.isSelected ? PH.un_thumbUpDailyApi : PH.thumbUpDailyApi
        
        PlayFeedBack()
        
        self.thumbUpBtn.isSelected = !self.thumbUpBtn.isSelected
        
        self.model?.dailyContent.isThumbUp = !m.dailyContent.isThumbUp
        if self.thumbUpBtn.isSelected{
            self.model?.dailyContent.thumpCount += 1
        }else{
            self.model?.dailyContent.thumpCount -= 1
        }
        
        let str = (self.model?.dailyContent.thumpCount ?? 0).st_number_description() + "  "
        
        self.thumbUpBtn.setTitleForAllStates(str)
        
        if api == PH.thumbUpDailyApi{
            
            ST_BTGlobalDataCenter.shared.thumbUpDailyEvent(dailyType: m.dailyContent.name, liked_user_id: m.userInfo.accid, daily_id: m.dailyId)
        }
        
        JVrequest(api,parameters: ["target_accid":m.userInfo.accid,"daily_content_id":m.dailyId], success: { (json) in
            
            self.thumbUpBtn.isUserInteractionEnabled = true
            
            NotificationCenter.default.post(name: Notification.Name.thumbUpDaily, object: nil, userInfo: ["fromController":self.parentViewController ?? 0,"isThumbUp":self.thumbUpBtn.isSelected,"id":m.dailyId])
            
        }) { (code, err) in
            
            self.thumbUpBtn.isUserInteractionEnabled = true
            
            self.parentViewController?.toast(text: err)
        }
        
    }
    
    @objc fileprivate func pushSomeDailyHandle(){
        
        
        let vc = ST_SomeOneDailyViewController()
        
        vc.dailyModel = self.model?.dailyContent.conver_to_daily_base_model()
        
        self.parentViewController?.navigationController?.pushViewController(vc)
    }
    
    @objc fileprivate func push_user_center_handle(){
        
        guard let m = model else{
            return
        }
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = m.userInfo.accid
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
    }
    
    @objc fileprivate func follow_click_handle(){
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self.parentViewController) {
            return
        }
        
        guard let m = self.model else { return  }
        
        self.follow_btn.isUserInteractionEnabled = false
        
        let info = ST_MatchUserInfo(accid: m.userInfo.accid, avatar: m.userInfo.avatar, nickname: m.userInfo.nickname)
        
        self.follow_btn.isHidden = true
        
        PairsLikeAction(info: info, likeAction: true, isReceive: false, fromVC: self.parentViewController) { (code, err , matched) in
            
            self.follow_btn.isUserInteractionEnabled = true
            
            if code == 1{
            
                matched?()
                
                self.model?.userInfo.isAttention = true
                
                self.follow_btn.isHidden = true
                
            }else {
                
                if let e = err{ self.parentViewController?.toast(text: e) }
                
                self.follow_btn.isHidden = false
            }
            
            
        }
        
        
        /*
        guard let model = self.model else{return}
        
        let info = ST_MatchUserInfo.init(accid: model.userInfo.accid, avatar: model.userInfo.avatar, nickname: model.userInfo.nickname)
        
        FollowBehavior(info: info, followControl: follow_btn) { (matched, err) in
            
            if let e = err{
                self.parentViewController?.toast(text: e)
            }else{
                
                self.model?.userInfo.isAttention = self.follow_btn.isSelected
            }
        }
        */
    }
    
}
